package com.lay.http.core;

import com.google.gson.Gson;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by Administrator on 2019-11-18.
 */

public class UploadRequest extends RequestBody {
    private File uploadFile;

    public UploadRequest(String url) {
        super(url);
    }

    public File getUploadFile() {
        return uploadFile;
    }

    public void setUploadFile(File uploadFile) {
        this.uploadFile = uploadFile;
    }

    @Override
    public ResponseBody send() {
        if(uploadFile == null){
            throw new NullPointerException("file == null");
        }
        if(!uploadFile.exists()){
            throw new IllegalArgumentException("file is not exist");
        }
        final String newLine = "\r\n";
        final String preFix = "--";
        final String bounDary = "----WebKitFormBoundaryCXRtmcVNK0H70msG";

        PostResponse responseBody = new PostResponse();
        OutputStream out = null;
        HttpURLConnection connection = null;
        InputStream fileIn = null;
        InputStream inputStream = null;
        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection)httpUrl.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(getConnectTimeout());
            connection.setReadTimeout(getReadTimeout());
            connection.setRequestMethod("POST");
            if(getHeaders().get("Connection") != null){
                connection.setRequestProperty("Connection", getHeaders().get("Connection").toString());
            } else {
                connection.setRequestProperty("Connection", "Keep-Alive");
            }
            if(getHeaders().get("Charset") != null){
                connection.setRequestProperty("Charset", getHeaders().get("Charset").toString());
            } else {
                connection.setRequestProperty("Charset", "UTF-8");
            }
            if(getHeaders().get("Content-Type") != null){
                connection.setRequestProperty("Content-Type", getHeaders().get("Content-Type").toString());
            } else {
                connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + bounDary);
            }
            connection.setRequestProperty("User-Agent", "(Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36)");
            connection.connect();
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            //上传普通文本文件
            Map<String, Object> params = getParams();
            if (params.size() != 0 && params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    //获取参数名称和值
                    String key = entry.getKey();
                    String value = params.get(key).toString();
                    //向请求中写分割线
                    dos.writeBytes(preFix + bounDary + newLine);
                    //向请求拼接参数
                    dos.writeBytes("Content-Disposition: form-data; " + "name=\"" + key + "\"" + newLine);
                    //向请求中拼接空格
                    dos.writeBytes(newLine);
                    //写入值
                    dos.writeBytes(URLEncoder.encode(value, "utf-8"));
                    //dos.writeBytes(value);
                    //向请求中拼接空格
                    dos.writeBytes(newLine);
                }
            }

            String filePrams = "file";
            String fileName = uploadFile.getName();
            //向请求中加入分隔符号
            dos.write((preFix + bounDary + newLine).getBytes());
            //将byte写入
            dos.writeBytes("Content-Disposition: form-data; " + "name=\"" + URLEncoder.encode(filePrams, "utf-8") + "\"" + "; filename=\"" + URLEncoder.encode(fileName, "utf-8") + "\"" + newLine);
            dos.writeBytes(newLine);
            //上传文件
            fileIn = new FileInputStream(uploadFile);
            if (!params.isEmpty()) {
                //向请求中写分割线
                //把file装换成byte
                int size = 1024 * 1024;
                int len = 0;
                byte[] buffer = new byte[size];
                while(true){
                    len = fileIn.read(buffer);
                    if(len < 0){
                        fileIn.close();
                        break;
                    }
                    out.write(buffer, 0, len);
                    out.flush();
                }
                //向请求中拼接空格
                dos.writeBytes(newLine);
            }
            dos.writeBytes(preFix + bounDary + preFix + newLine);

            responseBody.setReaponseCode(connection.getResponseCode());
            responseBody.setHeader(connection.getHeaderFields());
            inputStream = connection.getInputStream();
            responseBody.handle(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileIn != null) {
                try {
                    fileIn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null){
                connection.disconnect();
            }
        }
        return responseBody;
    }
}
